  function kn=md2rc(k,t);
% function knew=md2rc(k,t);
%
% Convert a multidimensional (r,c,p,b) matrix k into a 
% column row matrix 
% Use for instance for the output of multiple chains 
% Code assumes the highest dimension corresponds to the different chains 
% t corresponds to the dimension of the draws 
% knew is dim(b)*dim(t) rows and remaining columns 
%
% Alejandro Justiniano @2004 
% Please let me know of any problems with this function at 
% ajustiniano@imf.org

% 
% Note: output is such that the 1st draw for all chains is
% first, 2nd draws for all chains stacked 2nd and so on. 
% ie. algorithm stacks draws at state i for all chains 
if nargin < 2; 
    error('Must provide t, indicating the dimension of the draws'); 
end; 
sv=size( k );
ne=length(sv);
if t > ne; 
    error('Dimension indicator t exceeds dimension of the matrix'); 
end; 
if ne ==2; 
    if t==1; 
        kn=k; 
    else 
        kn=k'; 
    end; 
    return; 
end; 
vd=1:ne; 
vdtr=vd;
if t==ne; 
    di=t; 
else 
    di=[ne t]; 
end
vdtr(di)=[]; 
vdtr=sort(vdtr); 
v=[ vd(di) vdtr ];
kn=permute(k,v); 
nr=prod(sv(di)); 
nc=prod(sv(vdtr)); 
kn=reshape(kn(:),nr,nc); 